package implicits

/**
 * Created by yz on 22/9/2021
 */

import play.api.libs.json.{JsObject, Json}

import scala.collection.mutable
import scala.language.implicitConversions
import implicits.Implicits._
import tool.Tool

import java.io.File

trait BlastTool {

  implicit class GetDataByTable(tmpDir: File) {
    val contentLines = Tool.getOutTableFile(tmpDir).txtLines.drop(1).map(x => x.map(_.trim))

    val sort1 = Tool.getSeqFile(tmpDir).lines.filter(_.startsWith(">")).map { x =>
      x.tail.split(" ").head
    }

    def getSyntenyData: Array[JsObject] = {
      contentLines.map { xlx =>
        (xlx(5), xlx(11), xlx(7), xlx(8), xlx(9), xlx(13), xlx(14))
      }.groupBy(_._1).flatMap { x =>
        val sort2 = contentLines.filter(_ (5) == x._1).map(_ (11)).distinct
        x._2.groupBy(_._2).map { y =>
          val aName = x._1
          val aMin = 1
          val aMax = y._2.head._3.toInt
          val rectA = y._2.map { z =>
            Array("", z._4, z._5)
          }

          val bName = y._1
          val bRange = y._2.flatMap(z => Array(z._6.toInt, z._7.toInt))
          val bMin = bRange.min
          val bMax = bRange.max
          val rectB = y._2.map { z =>
            Array("", z._6, z._7)
          }

          val relate = y._2.zipWithIndex.map(z => Array(z._2 + 1, z._2 + 1))

          val data = Json.obj("A" -> Json.obj("name" -> aName, "min" -> aMin, "max" -> aMax,
            "seqType" -> "Query", "rect" -> rectA),
            "B" -> Json.obj("name" -> bName, "min" -> bMin, "max" -> bMax, "seqType" -> "Subject", "rect" -> rectB))

          val i1 = sort1.indexOf(x._1) + 1
          val i2 = sort2.indexOf(y._1) + 1
          Json.obj("data" -> data, "relate" -> relate, "index" -> (i1 + "-" + i2))
        }
      }.toArray

    }
  }
}

